package com.athl.netty.nio.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author hl
 * @Data 2020/8/30
 */
public class NioClient01 {

    private final String host = "127.0.0.1";
    private final Integer port = 6666;
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    public NioClient01() throws IOException {
        selector = Selector.open();
        // 连接服务器
        socketChannel = SocketChannel.open(new InetSocketAddress(host, port));
        // 将channel注册到Selector
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
        // 的到username
        username = socketChannel.getLocalAddress().toString();
        System.out.println(username + "客户端, ok了。。。");
    }

    /**
     * 发送消息   buffer --> socketChannel
     *
     * @param msg
     */
    public void sendInfo(String msg) {
        msg = username + "说:" + msg;
        try {
            socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读数据 socketChannel --> buffer
     */
    public void readInfo() {
        try {
            int count = selector.select();
            if (count > 0) {
                // 有可用通道
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isReadable()) {
                        SocketChannel sc = (SocketChannel) selectionKey.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        int read = sc.read(buffer);
                        if (read > 0) {
                            String msg = new String(buffer.array());
                            System.out.println(msg.trim());
                        }
                    }
                    iterator.remove();
                }
            }/* else {
                System.out.println("无可用通道");
            }*/
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        NioClient01 nioClient01 = new NioClient01();
        // 读取数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    nioClient01.readInfo();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        // 发送数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                Scanner scanner = new Scanner(System.in);
                while (scanner.hasNextLine()) {
                    String s = scanner.nextLine();
                    nioClient01.sendInfo(s);
                }
            }
        }).start();
    }
}
